﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;

namespace PS3Helpers.Helpers
{
    public class WindowsFileIconHelper
    {
        [StructLayout(LayoutKind.Sequential)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        private const uint SHGFI_ICON = 0x100;
        private const uint SHGFI_LARGEICON = 0x0;    // 'Large icon
        private const uint SHGFI_SMALLICON = 0x1;    // 'Small icon

        [DllImport("shell32.dll")]
        private static extern UInt32 SHGetFileInfo(string pszPath,
                                    uint dwFileAttributes,
                                    ref SHFILEINFO psfi,
                                    uint cbSizeFileInfo,
                                    uint uFlags);

        public static Icon GetIconForFile(string filename, bool largeicon)
        {
            uint flags = SHGFI_ICON;
            if (largeicon) flags = flags | SHGFI_LARGEICON;
            else flags = flags | SHGFI_SMALLICON;

            SHFILEINFO shinfo = new SHFILEINFO();
            UInt32 res = SHGetFileInfo(filename, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), flags);

            if (res == 0)
                return null;

            return Icon.FromHandle(shinfo.hIcon);
        }
    }
}
